import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    cart: [
      { id: 1, name: '手机', price: 1000, quantity: 1 },
      { id: 2, name: '电脑', price: 2000, quantity: 1 },
      { id: 3, name: '键盘', price: 200, quantity: 2 }
    ]
  },
  mutations: {
    INCREMENT_QUANTITY(state, productId) {
      const product = state.cart.find(p => p.id === productId)
      if (product) product.quantity++
    },
    DECREMENT_QUANTITY(state, productId) {
      const product = state.cart.find(p => p.id === productId)
      if (product && product.quantity > 1) product.quantity--
    },
    ADD_PRODUCT(state, product) {
      state.cart.push({
        id: Date.now(),
        ...product,
        quantity: 1
      })
    },
    REMOVE_PRODUCT(state, productId) {
      state.cart = state.cart.filter(p => p.id !== productId)
    }
  },
  getters: {
    totalPrice: state => {
      return state.cart.reduce((total, product) => 
        total + product.price * product.quantity, 0
      )
    }
  }
})